<?php
	require_once 'util/error.php';
	require_once 'util/dbconnection.php';
	
	// 检查form提交的参数
	$msg_author = isset($_POST['author'])?strip_tags($_POST['author']):null;
	$comment_author_email = ( isset($_POST['email']) ) ? trim($_POST['email']) : null;
	$comment_author_phone = ( isset($_POST['phone']) ) ? trim($_POST['phone']) : null;
	$comment_author_other = ( isset($_POST['other']) ) ? trim($_POST['other']) : null;
	$comment_content  = ( isset($_POST['content']) ) ? trim($_POST['content']) : null;
	$client_ip = $_SERVER['REMOTE_ADDR'];
	//echo "msg_author:".$msg_author;
	
	if( '' == $msg_author )
		site_die("姓名不能为空!", "提交错误");
	else if( '' == $comment_author_email &&
			'' == $comment_author_phone && ''==$comment_author_other)
		site_die("联系方式必须填写一项!", "提交错误");
	else if( '' == $comment_content  )
		site_die( "留言内容不能为空!" );
	
	// 验证email
	if( $comment_author_phone != '' ){
		if(!preg_match('/^[0-9-]+$/', $comment_author_phone)){
			site_die( "您输入的电话似乎不合法 !" );
		}
	}
	// 验证phone为数字
	if( $comment_author_email != '' ){
		if(!preg_match('/^[_0-9A-Za-z]+@([0-9a-zA-Z]+.)+[a-z]+$/', $comment_author_email)){
			site_die( "您输入的email似乎不合法 !" );
		}
	}
	
	// 先检测提交的内容是否存在于cookie，防止重复提交
	$pa =  explode('/', $_SERVER['PHP_SELF']);
	$cookie_path = "";
	for( $i = 1; $i < count($pa)-1; $i++ ){
		$cookie_path .= "/".$pa[$i];
	}
	$cookie_domain = $_SERVER['HTTP_HOST'];
	
	// 所有信息验证完毕，提交数据库
	$fba = array( "author" => $msg_author,
				  "email" => $comment_author_email,
				"phone" => $comment_author_phone,
				"comment" => nl2br($comment_content),
				"other" => $comment_author_other,
				"msger_ip" => $client_ip
				 );
	
	connect_db();
	// 根据author和email | phone | other取content，相同则提示重复评论
	if(check_feedback($fba)){
		site_die("检测到重复留言，请重新留言");
	}
				 
	$result = commit_feedback($fba);
	if( $result == false ){
		site_die( "提交评论失败，请重试" );
	}
	close_db();
	
	// 数据库提交完毕后，写入cookie
	setcookie("feedback_author", $msg_author,  time()+30000000);
	if( $comment_author_email != '' ){
		setcookie("feedback_contact_email", $comment_author_email,  time()+30000000);
	}
	if( $comment_author_phone != '' ){
		setcookie("feedback_contact_phone", $comment_author_phone,  time()+30000000);
	}
	
	$backurl = $_POST['backurl'];
	if( isset($backurl) && ''!=$backurl )
		site_redirct( $backurl );
?>